<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-04 10:32:51
 * @Description  : 多级菜单
-->

<template>
  <div
    class="father text-textColor text-[14px]"
    v-for="item in items"
    :key="item.id"
  >
    <div
      class="item flex items-center h-[40px] hover:bg-menuHover cursor-pointer"
      :class="{ active: defaultIndex === item.id }"
      :style="{ paddingLeft: `${item.level * 24}px` }"
      @click.stop="handleMenuClick(item)"
    >
      <div class="icon mr-[10px]">
        <SvgIcon
          :icon="item.icon"
          :color="!isActive(item) ? '#9193a5' : '#fff'"
          size="16px"
        ></SvgIcon>
      </div>
      <div class="title flex-1">{{ item.title }}</div>
      <div
        class="arrow mr-[16px]"
        v-if="hasChildren(item)"
        :class="{ rotate: isOpen(item) }"
      >
        <SvgIcon icon="xiala" color="#9193a5" size="10px"></SvgIcon>
      </div>
    </div>
    <MyTransition>
      <div class="sub" v-if="hasChildren(item)" v-show="isOpen(item)">
        <wp-menu2
          :items="item.children"
          :default-index="defaultIndex"
          :open-items="props.openItems"
          @changeActiveIndex="handleActiveIndex"
          @toggle-menu="handleToggleMenu"
        ></wp-menu2>
      </div>
    </MyTransition>
  </div>
</template>

<script lang="ts" setup>
import type { IndexObj } from '@/types/commom'

const props = defineProps<{
  items: IndexObj[]
  defaultIndex: number
  openItems: any[]
}>()

const emits = defineEmits<{
  (e: 'changeActiveIndex', value: IndexObj): void
  (e: 'toggleMenu', value: IndexObj): void
}>()

const handleMenuClick = (item: IndexObj) => {
  if (!hasChildren(item)) {
    emits('changeActiveIndex', item)
  } else {
    handleToggleMenu(item)
  }
}

const isOpen = (item: IndexObj) => {
  return props.openItems.includes(item.id)
}

const isActive = (item: IndexObj) => {
  return props.defaultIndex === item.id
}

const handleToggleMenu = (item: IndexObj) => {
  emits('toggleMenu', item)
}

const hasChildren = (item: IndexObj) => {
  return item.children && item.children.length > 0
}

const handleActiveIndex = (value: IndexObj) => {
  emits('changeActiveIndex', value)
}
</script>

<style scoped lang="scss">
.active {
  background: $primaryColor !important;
}

.father {
  .item {
    transition: background 0.3s;

    &:active {
      background-color: rgba($color: #fff, $alpha: 0.2);
    }
  }
}

.arrow {
  transition: all 0.3s;
  transform: rotateZ(-90deg);
  &.rotate {
    transform: rotateZ(0deg);
  }
}
</style>
